//
//  Home.swift
//  WatermarkCamera
//
//  Created by AxcLogo on 4/7/2024.
//

import UIKit
import NSObject_Rx
import AxcBedrock

/// 水印照片结果
typealias PhotoResult = (
    watermarkPhoto: UIImage,
    standardPhoto: UIImage,
    watermarkModel: WatermarkDetailModel?
)

// MARK: - [HomeVC]

class HomeVC: BaseVC {
    let vm = HomeVM()

    /// 是否开启重力感应反馈
    var isAccelerometerFeedback: Bool = true

    /// 拍照的画幅
    var photoAspectRatio: Eyepiece.AspectRatio?

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 重感反馈
        isAccelerometerFeedback = true
        MotionTool.shared.start()
        // 顶部菜单隐藏
        headerMenuShow(false)
        controlView.viewWillAppear(self)
        LocationManager.shared.startLocation()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 开启相机(保险起见)
        startCamera()
        // 重置曝光
        cameraView?.setExposure(0)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 重感反馈
        isAccelerometerFeedback = false
        MotionTool.shared.stop()
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if UserDefaults.standard.object(forKey: "TheFirstHome") == nil {
            UserDefaults.standard.set("asd", forKey: "TheFirstHome")
            vm.setWatermarkModel(.Create(name: "时间地点", imageName: "shijiandidian").set(type: .timeAddress))
        }
        
        let size = CPlusPlusBridge.getFreeDiskSpace()
        print(size)
        
        DateManager.shared.requestDate()
        
        // 弹窗调度
        vm.alertScheduler()

        // 同步本地相册列表
        vm.syncLocalAlbumList()

    }

    override func bindForwardAction() {
        viewActionBind()
    }

    override func createUI() {
        super.createUI()
        navView.isHidden = true

        addSubview(headerView)
        addSubview(cameraContentView)
        addSubview(watermarkContentView) // 相机水印视图
        addSubview(controlView) // 相机控制视图
        headerView.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: StatusBarHeight + 44)
        headerView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(StatusBarHeight + 44)
        }
        addSubview(footerView) // 底部拍摄工具栏
        addSubview(modeView) // 模式选择视图
        // 顶部菜单
        addSubview(menuView)
        menuView.snp.remakeConstraints { make in
            make.top.equalTo(headerView.snp.bottom).offset(8)
            make.left.equalTo(StandardEdge.left)
            make.right.equalTo(-StandardEdge.right)
            make.height.equalTo(70)
        }

        // 视频录制计时器
        addSubview(videoRecordingLabel)
        videoRecordingLabel.snp.makeConstraints { make in
            make.bottom.equalTo(footerView.snp.top).offset(-4)
            make.centerX.equalToSuperview()
            make.size.equalTo(CGSize(width: 85, height: 35))
        }
        
        // 滤镜选择View
        addSubview(filterView)
        filterView.snp.makeConstraints { make in
            make.top.equalTo(footerView)
            make.left.right.bottom.equalToSuperview()
        }
        
        // 焦距倍数选择
        view.addSubview(focusAdjustView)
        let focusAdjustVH = focusAdjustView.fittedHeight()
        focusAdjustView.snp.makeConstraints { make in
            make.top.equalTo(headerView.snp.bottom).offset(120.0)
            make.right.equalTo(-12.0)
            make.height.equalTo(focusAdjustVH)
        }
        
        
        // 设置初始画幅
        setInitialAspectRatio()

        // 设置初始清晰度
        setInitialArticulation()

        // 设置重力感应
        deviceMotionGravitySensor()

        // 设置锁全部操作的视图
        addSubview(lockActionView)
        lockActionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        // 获取上一次使用的水印
        vm.getLastUseWatermark()
    }

    override func bindReverseAction() {
        // 应用回到前台
        AppStateManager.shared.becomeActive.subscribe(onNext: { [weak self] in
            guard let weakSelf = self else { return }
            // 更新水印
            weakSelf.updateWatermarkView()
            // 开启相机
            weakSelf.startCamera()
        }).disposed(by: rx.disposeBag)

        vm.addCameraViewRelay.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            weakSelf.addCameraView()
        }).disposed(by: rx.disposeBag)

        // 水印切换
        vm.watermarkRelay.subscribe(onNext: { [weak self] wmModel in
            guard let weakSelf = self else { return }
            weakSelf.watermarkContentView.setWatermark(model: wmModel)
        }).disposed(by: rx.disposeBag)

        // 本地数据库更新
        vm.localMediaAlbumPhotoListRelay.skip(1).subscribe(onNext: { [weak self] list in
            guard let weakSelf = self else { return }
            DispatchQueue.main.async { [weak self] in
                guard let weakSelf = self else { return }
                // 左下角预览按钮的图片替换
                weakSelf.setPreViewImage()
                weakSelf.footerView.localAlbumBtn.isEnabled = true
            }
        }).disposed(by: rx.disposeBag)

        // 图片处理完成
        vm.photoDisposeFinishRelay.subscribe(onNext: { [weak self] result in
            guard let weakSelf = self else { return } // 跳转逻辑
            // 直接保存，使用拍摄时的水印模型
            weakSelf.vm.saveImage(watermarkPhoto: result.watermarkPhoto,
                                  standardPhoto: result.standardPhoto,
                                  watermarkModel: result.watermarkModel)
        }).disposed(by: rx.disposeBag)
        
        // 时间更新监听
        DateManager.shared.networkDate.subscribe(onNext: { [weak self] value in
            AxcGCD.Main { [weak self] in
                guard let weakSelf = self else { return }
                weakSelf.updateVideoWatermarkScreenshot() // 更新水印截图
                weakSelf.vm.updateRecordingTimer() // 更新计时器
            }
        }).disposed(by: rx.disposeBag)
        
        // 视频已录制时间
        vm.videoRecordingTimeRelay.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            weakSelf.videoRecordingLabel.text = value
        }).disposed(by: rx.disposeBag)
        
        // 视频需要停止
        vm.videoStopRecordingRelay.subscribe(onNext: { [weak self] value in
            guard let weakSelf = self else { return }
            weakSelf.stopRecording(breakOffType: .timeOut)
        }).disposed(by: rx.disposeBag)
    }

    var cameraView: CameraView?

    /// 用于锁全屏操作的
    lazy var lockActionView: UIView = {
        let view = UIView()
        view.isHidden = true
        return view
    }()

    lazy var menuView: HomeMenuView = {
        let view = HomeMenuView()
        return view
    }()

    lazy var modeView: HomeModeView = {
        let view = HomeModeView()
        return view
    }()

    lazy var footerView: HomeFooterView = {
        let view = HomeFooterView()
        return view
    }()

    lazy var headerView: HomeHeaderView = {
        let view = HomeHeaderView()
        return view
    }()

    lazy var cameraContentView: CameraContentView = {
        let view = CameraContentView()
        view.backgroundColor = .black
        return view
    }()

    lazy var watermarkContentView: WatermarkContentView = {
        let view = WatermarkContentView()
        return view
    }()

    lazy var controlView: HomeControlView = {
        let view = HomeControlView()
        return view
    }()

    lazy var watermarkSelectView: SelectWatermarkPreviewView = {
        let view = SelectWatermarkPreviewView()
        return view
    }()

    lazy var videoRecordingLabel: UILabel = {
        let label = UILabel.Axc.Create(font: 22.axc.uiFont(weight: .bold),
                                       color: UIColor.white,
                                       alignment: .center)
        label.backgroundColor = "F54A45".axc.uiColor
        label.layer.cornerRadius = 4
        label.layer.masksToBounds = true
        label.isHidden = true
        return label
    }()
    
    private(set) lazy var focusAdjustView: HomeControlFocusAdjustView = {
        let view = HomeControlFocusAdjustView()
        view.set(scale: 1.0, isShowScales: false)
        return view
    }()
    
    /// 滤镜view
    private(set) lazy var filterView: HomeImageFilterView = {
        let view = HomeImageFilterView()
        view.items = vm.filterItems
        // 默认隐藏
        view.isHidden = true
        return view
    }()
}
